<template>
    <div style="height:100%;">
        <!--路径导航-->
        <div class="box path">
            首页 > 权限管理 > 用户管理
        </div>

        <!--内容-->
        <div class="box mains">
            <!--操作按钮-->
            <div class="buttons">
                <el-row>
                    <el-col :span="12" style="text-align:left;">
                        <el-button type="info" size="mini" @click="dialogAdd" icon="el-icon-plus">添加</el-button>
                        <el-button type="danger" size="mini" @click="eventDeleteAll" icon="el-icon-delete">批删
                        </el-button>
                    </el-col>
                    <el-col :span="12" style="text-align:right;">
                        <el-input type="text" size="mini" style="width:300px;"></el-input>
                        <el-button type="success" size="mini" icon="el-icon-search">查询</el-button>
                    </el-col>
                </el-row>
            </div>

            <!--显示列表-->
            <div class="contents">
                <el-table :data="listData" style="width:100%" @selection-change="tableSelectChange">
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column prop="empNo" label="工号" width="100"></el-table-column>
                    <el-table-column prop="name" label="姓名"></el-table-column>
                    <el-table-column label="状态" width="150">
                        <template slot-scope="scope">
                            <!-- if(scope.row.statue==0)  正常
                        else  禁用 -->
                            <template v-if="scope.row.statue == '0'">
                                <el-tag type="success" size="mini">正常</el-tag>
                            </template>
                            <template v-else>
                                <el-tag type="danger" size="mini">已禁用</el-tag>
                            </template>

                        </template>
                    </el-table-column>
                    <el-table-column prop="lastLoginTime" label="最后登录日期" width="180"></el-table-column>
                    <el-table-column label="操作" width="180">
                        <template slot-scope="scope">
                            <el-button type="info" size="mini" @click="dialogEdit(scope.row)" title="编辑">
                                <i class="el-icon-edit"></i>
                            </el-button>
                            <el-button type="warning" size="mini" @click="eventDelete(scope.row.id)" title="删除">
                                <i class="el-icon-delete"></i>
                            </el-button>
                            <el-button type="primary" size="mini" title="配置角色" @click="dialogConfigRole(scope.row.id)">
                                <i class="el-icon-setting"></i>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!--分页-->
            <div class="pages">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    current-page.sync="paged.pageIndex" :page-size="paged.pageSize" layout="total, prev, pager, next"
                    :total="paged.total">
                </el-pagination>
            </div>
        </div>


        <!--弹出层-->
        <div style="text-align:left;">
            <!--编辑用户-->
            <el-dialog :title="dialogEditTitle" :visible.sync="dialogEditVisible" width="35%">
                <el-form :model="editForm" label-width="100px">
                    <el-form-item label="工号">
                        <el-input size="mini" v-model="editForm.empNo" disabled style="width:90%;float: left;">
                        </el-input>
                        <label title="选择员工"
                            style="border:1px solid #dcdcdc; padding: 4px 5px; border-radius: 3px; cursor: pointer;"
                            @click="dialogEmployeeVisible = true">
                            ...
                        </label>
                    </el-form-item>
                    <el-form-item label="姓名">
                        <el-input size="mini" v-model="editForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="密码">
                        <el-input size="mini" v-model="editForm.password"></el-input>
                    </el-form-item>
                </el-form>
                <div>
                    <el-button type="danger" size="mini" @click="enevtSubmit">提交</el-button>
                </div>
            </el-dialog>

            <!--选择员工-->
            <el-dialog title="选择员工" :visible.sync="dialogEmployeeVisible" width="60%">
                <!--使用组件-->
                <EmployeeList @eventEmployee="eventEmployeeSelect" />
            </el-dialog>

            <!--配置角色-->
            <el-dialog title="配置角色" :visible.sync="dialogConfigRoleVisible">

                <!-- <el-checkbox :indeterminate="configRole.isIndeterminate" v-model="configRole.checkAll"
                    @change="handleCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="configRole.checkedCities" @change="handleCheckedCitiesChange">
                    <el-checkbox v-for="city in configRole.cities" :label="city" :key="city">{{ city }}</el-checkbox>
                </el-checkbox-group> -->


                <el-checkbox :indeterminate="configRole.isIndeterminate" v-model="configRole.checkAll"
                    @change="handleCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="configRole.checkedRoles" @change="handleCheckedCitiesChange">
                    <el-checkbox v-for="role in configRole.roles" :label="role.id" :key="role.id">{{ role.name
                    }}</el-checkbox>
                </el-checkbox-group>

                <div style="margin: 20px 0 10px 0;">
                    <el-button type="danger" @click="eventSubmitRole">提交</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import EmployeeList from '@/components/employee/List.vue'  //导入组件页面

export default {
    components: {
        EmployeeList  //声明该导入的组件页面为一个组件
    },
    data() {
        return {
            id: '',
            listData: [],
            selectTableValue: [],
            dialogEditTitle: '添加用户',
            dialogEditVisible: false,
            dialogEmployeeVisible: false,//弹出员工列表
            dialogConfigRoleVisible: false,
            editForm: {
                "empNo": "",
                "name": "",
                "password": "",
            },
            paged: {
                pageIndex: 1,
                pageSize: 8,
                total: 0
            },
            configRole: {
                checkAll: false,
                isIndeterminate: true,
                cities: ['管理员', '经理', '主管', '职员'],  //所有的角色列表
                checkedCities: ['主管', '职员'],  //选中的角色列表
                roles: [
                    { id: '1', name: '管理员r' },
                    { id: '2', name: '经理r' },
                    { id: '3', name: '主管r' },
                    { id: '4', name: '职员r' },
                ],
                checkedRoles: [],
            }
        }
    },
    mounted() {
        this.initData()
    },
    methods: {
        //员工选择（用来接收子组件传值）
        eventEmployeeSelect(row) {
            this.editForm.empNo = row.eNo
            this.editForm.name = row.name
            this.dialogEmployeeVisible = false
        },

        //表格选择事件
        tableSelectChange(val) {
            this.selectTableValue = val
            console.log(this.selectTableValue)
        },

        //弹出事件 - 添加按钮
        dialogAdd() {
            this.dialogEditVisible = true
            this.dialogEditTitle = "添加用户"
            this.editForm.empNo = ''
            this.editForm.name = ''
            this.editForm.password = ''
        },

        //弹出事件 - 编辑按钮
        dialogEdit(row) {
            this.dialogEditVisible = true
            this.dialogEditTitle = "编辑用户"

            //将要编辑的数据绑定到表单的控件上（即反填）
            this.id = row.id  //id是要保存下来，方便修改的时候传递
            this.editForm.empNo = row.empNo
            this.editForm.name = row.name
            this.editForm.password = row.password
        },

        //弹出事件 - 配置角色
        dialogConfigRole(id) {
            this.id = id
            this.dialogConfigRoleVisible = true

            this.configRole.checkedRoles = [] //弹出的时候，原来其它的选择都清空
            //加载角色列表
            this.$http.get(this.$baseUrl + 'role', {
                params: {
                    pageIndex: 1,
                    pageSize: 100
                }
            }).then(res => {
                //console.log(res)
                this.configRole.roles = res.data.data
            })

            //加载用户已用的角色列表
            this.$http.get(this.$baseUrl + 'user/roles', {
                params: {
                    userId: id
                }
            }).then(res => {
                let d = res.data.data
                //console.log(d)
                if (d != null && d.length > 0) {
                    d.forEach(x => {
                        //将已用的角色ID，放到选择角色的这个变量里（用来反填）
                        this.configRole.checkedRoles.push(x.roleId)
                    })
                }
            })

        },
        //选择角色相关
        // handleCheckAllChange(val) {
        //     this.configRole.checkedCities = val ? this.configRole.cities : [];
        //     this.configRole.isIndeterminate = false;
        // },
        // handleCheckedCitiesChange(value) {
        //     let checkedCount = value.length;
        //     this.configRole.checkAll = checkedCount === this.configRole.cities.length;
        //     this.configRole.isIndeterminate = checkedCount > 0 && checkedCount < this.configRole.cities.length;
        // },

        handleCheckAllChange(val) {
            this.configRole.checkedRoles = val ? this.configRole.roles : [];
            this.configRole.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            //console.log(value)
            let checkedCount = value.length;
            this.configRole.checkAll = checkedCount === this.configRole.roles.length;
            this.configRole.isIndeterminate = checkedCount > 0 && checkedCount < this.configRole.roles.length;
        },
        //提交配置角色事件
        eventSubmitRole() {
            // console.log('user id：' + this.id)
            // console.log(this.configRole.checkedRoles)

            let data = {
                "userId": this.id,
                "rolesId": this.configRole.checkedRoles
            }
            this.$http.post(this.$baseUrl + 'user/config', data).then(res => {
                console.log(res)
            })
        },

        //编辑信息提交按钮事件
        enevtSubmit() {
            if (this.editForm.empNo == '') {
                this.$message('员工工号必须填写')
                return
            }

            let url = this.$baseUrl + 'user'
            let data = this.editForm

            //添加和修改用的是同一个表单，所以根据id是否为空来判断
            //（修改的时候需要根据id来修改，添加的时候id不用填，即为空）            
            if (this.id == '') {
                //添加
                this.$http.post(url, data).then(x => {
                    this.$message(x.data.message)
                    if (x.data.code == 200) {
                        this.dialogEditVisible = false
                        this.initData()
                    }
                })
            }
            else {
                //修改
                data.id = this.id
                this.$http.put(url, data).then(x => {
                    this.$message(x.data.message)
                    if (x.data.code == 200) {
                        this.dialogEditVisible = false
                        this.initData()
                    }
                })
            }
        },

        //批量删除按钮事件
        eventDeleteAll() {
            let data = []

            //指删除时，删除选中的多条（选中的数据是根据table的选择改变事件中获取）
            //删除时，后台接口参数只需要id，所以在这里再进行遍历一下，将所有选中的id拿到
            this.selectTableValue.forEach(x => {
                data.push(x.id)
            })


            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '是的，不犹豫',
                cancelButtonText: '不，再考虑一下',
                type: 'warning'
            }).then(() => {
                this._delete(data)
            })

        },
        //单删除按钮事件
        eventDelete(id) {
            let data = []
            data.push(id)  //单删时，只删除一条记录（删除按钮在插槽中，所以用scope.row.di传值过来）
            if (confirm('确认要删除该条记录吗?')) {
                this._delete(data)
            }

        },
        //删除功能的封装
        //（后台封装的参数是 多个id字符串 :[List<string> ids]）
        _delete(data) {
            //在axios.delete的方法中，参数是两个 delete(url[,config])),
            //和get的参数是一样，所以在写法上需要用大括号{}包括，get的时候是用params,delete用data
            this.$http.delete(this.$baseUrl + 'user', { data: data }).then(res => {
                this.$message(res.data.message)
                if (res.data.code == 200)
                    this.initData()
            })
        },

        //初始化数据（页面在加载的时候执行，或点查询按钮的时候可以执行）
        initData() {
            this.$http.get(this.$baseUrl + 'user').then(x => {
                //console.log(x)
                this.listData = x.data.data
            })
        },
        //分页相关事件
        handleSizeChange(val) {
            this.paged.pageSize = val
            this.initData()
        },
        handleCurrentChange(val) {
            this.paged.pageIndex = val
            this.initData()
        }
    }
}
</script>

<style >
.mains {
    height: calc(100% - 45px);
}

.box {
    background: rgb(238, 240, 241);
}

.path {
    border-left: 4px solid darkorange;
    height: 35px;
    line-height: 35px;
    text-align: left;
    padding-left: 15px;
    font-size: 12px;
}

.buttons,
.contents {
    margin-top: 10px;
    padding-left: 15px;
    padding-top: 10px;
    padding-right: 15px;
}

.contents {
    height: calc(100% - 120px);
}

.pages {
    text-align: center;
    padding-right: 15px;
    margin-top: 10px;
}

.el-table {
    height: 100%;
}

.el-pagination button:disabled,
.el-pagination .btn-next,
.el-pagination .btn-prev,
.el-pager li {
    background-color: rgb(238, 240, 241);
}

.el-dialog__body {
    padding: 10px;
}
</style>